<?PHP

class OP_TaggedPostsWidget extends OP_WidgetTemplate{		
	function render(){
		$extratag = strlen($this->values['tags']) > 0 ? ' '.$this->values['tags'] : '';

		$tags = str_replace(' ','-',$this->values['tags']); // sensitive to tags with spaces 
		$tags = str_replace(',',' ',$tags); // must be space separated for wordpress query object
		
		$quantity = 10;
		$r = new WP_Query(array('tag'=>$tags, 'showposts' => $quantity, 'what_to_show' => 'posts', 'nopaging' => 0, 'post_status' => 'publish'));
		if ($r->have_posts()){
			echo $this->values['before_title'] . $this->values['title'] . $this->values['after_title'],
				'<ul>';
			while ($r->have_posts()){
				$r->the_post();
				echo '<li><a href="';
				the_permalink();
				echo '">';
				
				if (get_the_title()){
					the_title();
				} 
				else{
					the_ID();
				}
				echo '</a></li>';
			}
			echo '</ul>';
			wp_reset_query();
		}
	}
	
	function do_post($post){
		$title = strip_tags(stripslashes($post['title']));
		$tags = strip_tags(stripslashes($post['tags']));
		$quantity = (int) $post["quantity"];
		
		return compact( 'title','tags','quantity');
	}
	
	function options(){
		extract($this->values);
		$title = attribute_escape($title);
		$tags = attribute_escape($tags);
		
		echo '<p><label for="tagged_posts-title-'.$this->values['number'].'">'._e('Title:').' <input class="widefat" id="tagged_posts-title-'.$this->values['number'].'" name="widget_op_tagged_posts['.$this->values['number'].'][title]" type="text" value="'.$this->values['title'].'" /></label></p>',
			'<label>Tags to use:</label>',
			'<input class="widefat" type="text" id="tagged_posts-tags-'.$number.'" name="widget_op_tagged_posts['.$number.'][tags]" value="'.wp_specialchars($tags, true).'" />',
			'<small>separate with commas</small>',
			'<p>',
			'<p>',
				'<label for="tagged_posts-quantity-'.$this->values['number'].'">'._e('Number of posts to show:').' <input style="width: 25px; text-align: center;" id="tagged_posts-quantity-'.$this->values['number'].'" name="widget_op_tagged_posts['.$this->values['number'].'][quantity]" type="text" value="'.$this->values['quantity'].'" /></label>',
				'<br />',
					'<small>(at most 15)</small>',
			'</p>';
	}

}

$widget = new OP_Widget('tagged_posts');
$widget->setMeta('OP Tagged Posts','Show tagged posts in a list');
$widget->setDefaults(array('title'=>'','quantity'=>5,'tags'=>''));

$opw_tagged_posts = new OP_TaggedPostsWidget($widget);
add_action('widgets_init', array($opw_tagged_posts, 'init'));
?>